package datatypes

import (
	"sync"
)

//SICharacter 当前登录的角色
type SICharacter interface {
	ID() int64
	User() int64
}

//SIContent session存储的结构
type SIContent interface {
	Token() string
	User() int64
	Logined() SICharacter //当前登录的人物ID
	Switch(logined SICharacter) SICharacter
}

//NewSIContent 返回SIContext
func NewSIContent(token string, user int64) SIContent {
	return &siContent{
		token:    token,
		user:     user,
		logined:  nil,
		rwLocker: &sync.RWMutex{},
	}
}

type siContent struct {
	token    string      //session
	user     int64       //当前登录的账户
	logined  SICharacter //当前账户登录的人物
	rwLocker *sync.RWMutex
}

func (si *siContent) Token() string {
	return si.token
}

//UserID 返回userID
func (si *siContent) User() int64 {
	return si.user
}

func (si *siContent) Logined() SICharacter {
	si.rwLocker.RLock()
	defer si.rwLocker.RUnlock()
	return si.logined
}

func (si *siContent) Switch(logined SICharacter) SICharacter {
	si.rwLocker.Lock()
	defer si.rwLocker.Unlock()
	var old SICharacter
	old, si.logined = si.logined, logined
	return old
}

type siCharacter struct {
	id   int64
	user int64
}

//NewSICharacter 返回已经登录的人物信息
func NewSICharacter(id int64, user int64) SICharacter {
	return &siCharacter{id: id, user: user}
}
func (c siCharacter) ID() int64 {
	return c.id
}

func (c siCharacter) User() int64 {
	return c.user
}
